<?php
namespace Chat\Controller;
use Common\Controller\AdminbaseController;

class AdminIndexController extends AdminbaseController{

	protected $chat_model;

	public function _initialize() {
		parent::_initialize();
		$this->chatlist_model = D("ChatMessage");
	}


	// 聊天列表
	public function index(){

		//条件-名称
		$content = I('content');
		if($content){
			$where['content'] = array('like',"%$content%");
		}

		//时间搜索
		$start_time=I('request.start_time');
		$end_time=I('request.end_time');
		if($end_time && $end_time){
			$where['a.create_time'] = array('exp','>'.strtotime($start_time).' and a.create_time <'.strtotime($end_time));
		}

		//数量
		$count=$this->chatlist_model-> alias('a')->where($where)->count();
		//分页
		$page = $this->page($count, 15);

		//查询结果作为结果查询，于是就有了下边这两个语句
		$db_prefix=C('DB_PREFIX');
		$subQuery  = $this->chatlist_model
			-> alias('a')
			-> field('a.*,b.mobile as from_mobile,b.user_nicename as from_nicename')
			-> join($db_prefix.'users b on a.msg_from = b.id')
			-> where($where)
			-> order('a.message_id desc')
			-> buildSql();

		$lists = $this->chatlist_model
			-> table($subQuery.' fromuser')
			-> field('fromuser.*,touser.mobile as to_mobile,touser.user_nicename as to_nicename')
			-> join($db_prefix.'users touser on fromuser.msg_to = touser.id')
			-> limit($page->firstRow, $page->listRows)
			-> order('fromuser.message_id desc')
			-> select();


		$this -> assign("page", $page->show('Admin'));
		$this->assign("formget",array_merge($_GET,$_POST));
		$this -> assign('lists',$lists);
		$this->display('index');
	}

	//删除
	public function delete() {
		$message_id = I('message_id');
		$result = $this->chatlist_model-> delete($message_id);
		$data = array(
			'status' => $result ? true : false,
			'info' => $result ? '' : '删除失败，ID：'.$result,
			'url' => '',
		);
		$this -> ajaxReturn($data);
	}

	/**
	 * 商品列表的批量操作
	 * @param string $type    处理类型 order排序
	 */
	public function indexBat($type='order') {
		if ($type == 'delete') {
			$ids = I('post.ids');
			if ($this->chatlist_model  -> delete(implode(',',$ids)) !== FALSE) {
				$this -> success('删除成功');
			} else {
				$this -> error('删除失败');
			}
		}
	}

}